package com.ssm.maven.core.admin;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.ssm.maven.core.util.ImageHelper;

@Controller
@RequestMapping("/upload")
public class UploadController
{

    private static Logger logger = LoggerFactory.getLogger(UploadController.class);

    private String allowPicSuffix = "jpg,png,gif,jpeg";// 允许图片格式

    private String allowMediaSuffix = "mp4";// 允许视频格式

    private long allowSize = 100L;// 允许文件大小不超过100M

    private String fileName;

    private String[] fileNames;

    public long getAllowSize() {
        return allowSize * 1024 * 1024;
    }

    public void setAllowSize(long allowSize) {
        this.allowSize = allowSize;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String[] getFileNames() {
        return fileNames;
    }

    public void setFileNames(String[] fileNames) {
        this.fileNames = fileNames;
    }

    /**
     * 
     * <p class="detail">
     * 功能：重新命名文件
     * </p>
     * 
     * @author wangsheng
     * @date 2014年9月25日
     * @return
     */
    private String getFileNameNew() {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return fmt.format(new Date());
    }

    /**
     * 功能：文件上传
     */
    public void uploads(MultipartFile[] files, String destDir, HttpServletRequest request, String allowSuffix)
            throws Exception
    {
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
        try
        {
            fileNames = new String[files.length];
            int index = 0;
            for (MultipartFile file : files)
            {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                if (allowSuffix.indexOf(suffix) == -1)
                {
                    throw new Exception("请上传允许格式的文件");
                }
                if (file.getSize() > getAllowSize())
                {
                    throw new Exception("您上传的文件大小已经超出范围");
                }
                String realPath = request.getSession().getServletContext().getRealPath("/");
                File destFile = new File(realPath + destDir);
                if (!destFile.exists())
                {
                    destFile.mkdirs();
                }
                String fileNameNew = getFileNameNew() + "." + suffix;//
                File f = new File(destFile.getAbsoluteFile() + "\\" + fileNameNew);
                file.transferTo(f);
                f.createNewFile();
                fileNames[index++] = basePath + destDir + fileNameNew;
            }
        }
        catch (Exception e)
        {
            throw e;
        }
    }

    /**
     * 功能：文件上传
     */
    public void upload(MultipartFile file, String destDir, HttpServletRequest request, String allowSuffix)
            throws Exception
    {
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
        try
        {
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            int length = allowSuffix.indexOf(suffix.toLowerCase());
            if (length == -1)
            {
                throw new Exception("请上传允许格式的文件");
            }
            if (file.getSize() > getAllowSize())
            {
                throw new Exception("您上传的文件大小已经超出范围");
            }

            String realPath = request.getSession().getServletContext().getRealPath("/");
            File destFile = new File(realPath + destDir);
            if (!destFile.exists())
            {
                destFile.mkdirs();
            }
            String fileNameNew = getFileNameNew();
            String originFileNameNew = fileNameNew + "." + suffix;
            File f = new File(destFile.getAbsoluteFile() + "/" + originFileNameNew);
            file.transferTo(f);
            f.createNewFile();

            if (Arrays.asList(allowPicSuffix.split(",")).contains(suffix.toLowerCase()))
            {
                // 压缩图片
                String compressFileNameNew = fileNameNew + "_720." + suffix;
                ImageHelper.scaleImage(destFile.getAbsoluteFile() + "/" + originFileNameNew, destFile.getAbsoluteFile()
                        + "/" + compressFileNameNew, 720, suffix);
                fileName = basePath + destDir + compressFileNameNew;
            }
            else
            {
                fileName = basePath + destDir + originFileNameNew;
            }
        }
        catch (Exception e)
        {
            throw e;
        }
    }

    @RequestMapping("/uploadPic")
    public String uploadPic(@RequestParam("file") MultipartFile file, HttpServletRequest request,
            HttpServletResponse response) throws IOException
    {
        try
        {
            upload(file, "/upload/pic/", request, allowPicSuffix);
            JSONObject json = new JSONObject();
            json.put("fileUrl", getFileName());
            response.getWriter().print(json.toJSONString());
        }
        catch (Exception e)
        {
            logger.error("uploadPic error", e);
            JSONObject json = new JSONObject();
            json.put("errcode", -1);
            json.put("message", e.getMessage());
            response.getWriter().print(json.toJSONString());
        }
        return null;
    }

    @RequestMapping("/uploadFile")
    public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("allowSuffix") String allowSuffix,
            HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        try
        {
            upload(file, "/upload/file/", request, allowSuffix);
            JSONObject json = new JSONObject();
            json.put("fileUrl", getFileName());
            response.getWriter().print(json.toJSONString());
        }
        catch (Exception e)
        {
            logger.error("uploadFile error", e);
            JSONObject json = new JSONObject();
            json.put("errcode", -1);
            json.put("message", e.getMessage());
            response.getWriter().print(json.toJSONString());
        }
        return null;
    }

    /**
     * 功能：富文本图片上传
     */
    @RequestMapping("/uploadPicture")
    public String uploadPicture(@RequestParam(value = "imgFile") MultipartFile file, HttpServletRequest request,
            HttpServletResponse response) throws IOException
    {
        try
        {
            upload(file, "/upload/pic/", request, allowPicSuffix);
            JSONObject json = new JSONObject();
            json.put("error", 0);
            json.put("url", getFileName());
            response.getWriter().print(json.toJSONString());
        }
        catch (Exception e)
        {
            logger.error("uploadPic error", e);
            JSONObject json = new JSONObject();
            json.put("error", -1);
            json.put("message", e.getMessage());
            response.getWriter().print(json.toJSONString());
        }
        return null;
    }

    /**
     * 功能：富文本视频上传
     */
    @RequestMapping("/uploadMedia")
    public String uploadMedia(@RequestParam(value = "mediaFile") MultipartFile file, HttpServletRequest request,
            HttpServletResponse response) throws IOException
    {
        try
        {
            upload(file, "/upload/media/", request, allowMediaSuffix);
            JSONObject json = new JSONObject();
            json.put("error", 0);
            json.put("url", getFileName());
            response.getWriter().print(json.toJSONString());
        }
        catch (Exception e)
        {
            logger.error("uploadPic error", e);
            JSONObject json = new JSONObject();
            json.put("error", -1);
            json.put("message", e.getMessage());
            response.getWriter().print(json.toJSONString());
        }
        return null;
    }

}
